package vn.edu.uit.chemistry.utilities;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OptionalDataException;
import java.net.Socket;
import java.util.Map;

import vn.edu.uit.chemistry.NhanFile;
import vn.edu.uit.chemistry.protocol.BaiCu;
import vn.edu.uit.chemistry.protocol.BaiGiang;
import vn.edu.uit.chemistry.protocol.BatKy;
import vn.edu.uit.chemistry.protocol.CapNhatGame;
import vn.edu.uit.chemistry.protocol.CapNhatKiemTra15;
import vn.edu.uit.chemistry.protocol.KetQuaKiemTra15;
import vn.edu.uit.chemistry.protocol.Message;
import vn.edu.uit.chemistry.protocol.ThongTinCaNhan;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Environment;

public class ClientThreadCommand implements Runnable {

	private Socket socket;
	private Thread thread;
	private ObjectOutputStream oos;
	private ObjectInputStream ois;
	Context ctx;

	public ClientThreadCommand(Socket sk, Context _ctx) throws IOException {
		System.out.println("Client connected Command");
		this.socket = sk;
		this.ctx = _ctx;
	}

	public void start() throws IOException {

		oos = new ObjectOutputStream(socket.getOutputStream());
		ois = new ObjectInputStream(socket.getInputStream());

		thread = new Thread(this);
		thread.start();
		while (!thread.isAlive()) {
			//
		}

	}

	public void stop() throws IOException {

		if (socket != null) {
			socket.shutdownInput();
			socket.shutdownOutput();
			socket.close();
		}
	}

	public void run() {
		try {
			while (true) {
				handleMsg((Message) ois.readObject());
			}
		} catch (OptionalDataException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void handleMsg(Message msg) throws IOException {
		if (msg instanceof ThongTinCaNhan) {
			diemDanh((ThongTinCaNhan) msg);
		} else if (msg instanceof BaiCu) {
			nhanFileBaiCu((BaiCu) msg);
		} else if (msg instanceof CapNhatKiemTra15) {
			capNhatKiemTra15((CapNhatKiemTra15) msg);
		} else if (msg instanceof KetQuaKiemTra15) {
			nhanDapAnKT15HS((KetQuaKiemTra15) msg);
		} else if (msg instanceof BatKy) {
			nhanBatKy((BatKy) msg);
		} else if (msg instanceof BaiGiang) {
			nhanTaiLieu((BaiGiang) msg);
		} else if (msg instanceof CapNhatGame) {
			capNhatGame((CapNhatGame) msg);
		} 

	}
	
	private void nhanBatKy(BatKy msg) throws IOException { // danh cho tai lieu bat ky
		String nameFile = ((BatKy) msg).nameFile;
		String total = ((BatKy) msg).sizeFile;
		String tenHS = ((BatKy) msg).sender;
		String mshs = ((BatKy) msg).mshs;
		String host = ((BatKy) msg).host;

		oos.writeObject(new BatKy(nameFile, total, tenHS, mshs, host));
		
		SharedPreferences prefs = ctx.getSharedPreferences("FILENHAN", 0);
		SharedPreferences.Editor editor = prefs.edit();
		editor.putString("kind", "BK");
		editor.putString("name", nameFile);
		editor.putString("size", total);
		editor.putString("sender", tenHS);
		editor.putInt("percent", 0);
		editor.putString("host", host);
		editor.commit();
		
		prefs = ctx.getSharedPreferences("Path", 0);
		editor = prefs.edit();
		editor.putString("pos", "bat ky");
		editor.commit();
		
		Intent intent = new Intent(ctx, NhanFile.class);
		ctx.startActivity(intent);
	}
	
	private void nhanTaiLieu(BaiGiang msg) throws IOException { // danh cho tai lieu
		String nameFile = ((BaiGiang) msg).nameFile;
		String total = ((BaiGiang) msg).sizeFile;
		String tenHS = ((BaiGiang) msg).sender;
		String mshs = ((BaiGiang) msg).mshs;
		String host = ((BaiGiang) msg).host;

		oos.writeObject(new BaiGiang(nameFile, total, tenHS, mshs, host));
		
		SharedPreferences prefs = ctx.getSharedPreferences("FILENHAN", 0);
		SharedPreferences.Editor editor = prefs.edit();
		editor.putString("kind", "TL");
		editor.putString("name", nameFile);
		editor.putString("size", total);
		editor.putString("sender", tenHS);
		editor.putInt("percent", 0);
		editor.putString("host", host);
		editor.commit();
		
		prefs = ctx.getSharedPreferences("Path", 0);
		editor = prefs.edit();
		editor.putString("pos", "tai lieu");
		editor.commit();
		
		Intent intent = new Intent(ctx, NhanFile.class);
		ctx.startActivity(intent);
	}
	
	

	private void nhanFileBaiCu(BaiCu msg) throws IOException {
		String nameFile = ((BaiCu) msg).nameFile;
		String total = ((BaiCu) msg).sizeFile;
		String tenHS = ((BaiCu) msg).sender;
		String mshs = ((BaiCu) msg).mshs;
		String host = ((BaiCu) msg).host;

		SharedPreferences prefs = ctx.getSharedPreferences("DS_NOPBAICU", 0);
		SharedPreferences.Editor editor = prefs.edit();
		editor.putString(host, mshs + "#" + tenHS + "#" + nameFile + "#"
				+ total);
		editor.commit();

		oos.writeObject(new BaiCu(nameFile, total, tenHS, mshs, host));
	}

	private void diemDanh(ThongTinCaNhan msg) throws IOException {
		String mshs = ((ThongTinCaNhan) msg).mshs;
		String tenHS = ((ThongTinCaNhan) msg).ten;
		String host = ((ThongTinCaNhan) msg).host;
		
		if (mshs.equals("")) {
			SharedPreferences prefs = ctx.getSharedPreferences("DSNhom", 0);
			SharedPreferences.Editor editor = prefs.edit();
			editor.putString(host, tenHS+"#0");
			editor.commit();
			
			oos.writeObject(new ThongTinCaNhan(tenHS, mshs, host, "54321"));
		} else {
			SharedPreferences prefs = ctx.getSharedPreferences("DSHS", 0);
			Map<String, ?> keys = prefs.getAll();

			for (Map.Entry<String, ?> entry : keys.entrySet()) {
				if (entry.getKey().equals(mshs)) {
					prefs = ctx.getSharedPreferences("DSHS", 0);
					SharedPreferences.Editor editor = prefs.edit();
					editor.putString(mshs, tenHS + "#" + host);
					editor.commit();

					prefs = ctx.getSharedPreferences("PTNOPBAI", 0); // pham tram
																		// nop bai
					editor = prefs.edit();
					editor.putString(mshs, tenHS + "#0");
					editor.commit();

					prefs = ctx.getSharedPreferences("DS_NOPBAICU", 0);
					editor = prefs.edit();
					editor.putString(host, mshs + "#" + tenHS + "#nameFile#0");
					editor.commit();
					break;
				}
			}

			prefs = ctx.getSharedPreferences("Path", 0);
			SharedPreferences.Editor editor = prefs.edit();
			editor.putString("pos", "bai cu");
			editor.commit();
			
			oos.writeObject(new ThongTinCaNhan(tenHS, mshs, host, "54321"));
		}

	}

	private void capNhatKiemTra15(CapNhatKiemTra15 msg) {
		String tenHS = ((CapNhatKiemTra15) msg).hoten;
		String mshs = ((CapNhatKiemTra15) msg).mscn;
		String ipHS = ((CapNhatKiemTra15) msg).host;
		String hoanthanh = ((CapNhatKiemTra15) msg).hoanThanh;

		SharedPreferences prefs = ctx.getSharedPreferences("DSLamBai", 0);
		SharedPreferences.Editor editor = prefs.edit();
		editor.putString(ipHS, mshs + "#" + tenHS + "#" + hoanthanh + "#0");
		editor.commit();
	}

	private void nhanDapAnKT15HS(KetQuaKiemTra15 msg) {
		String tenHS = ((KetQuaKiemTra15) msg).sender;
		String mshs = ((KetQuaKiemTra15) msg).mshs;
		String ipHS = ((KetQuaKiemTra15) msg).host;
		String dapAnHS = ((KetQuaKiemTra15) msg).hsDapAn;

		luuFile(tenHS, mshs, dapAnHS);
		
		SharedPreferences prefs = ctx.getSharedPreferences("DSLamBai", 0);
		String value = prefs.getString(ipHS, "mshs#tenHS#0#0");
		value = value.substring(0, value.length() - 1);
		SharedPreferences.Editor editor = prefs.edit();
		editor.putString(ipHS, value + 1);
		editor.commit();
	}

	public void luuFile(String tenHS, String mshs, String dapAnHS) {

		File sdcard = Environment.getExternalStorageDirectory()
				.getAbsoluteFile();
		File file = new File(sdcard, "/hoa hoc/kiem tra/kt15/"+mshs+"_"+tenHS+".txt");

		FileOutputStream fos;
		byte[] data = new String(dapAnHS).getBytes();
		try {
			fos = new FileOutputStream(file);
			fos.write(data);
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
		}
	}
	
	public void capNhatGame(CapNhatGame msg) {
		String tenNhom = ((CapNhatGame) msg).tenNhom;
		String ipNhom = ((CapNhatGame) msg).ip;
		String result = ((CapNhatGame) msg).result;

		SharedPreferences prefs = ctx.getSharedPreferences("DSNhom", 0);
		SharedPreferences.Editor editor = prefs.edit();
		editor.putString(ipNhom, tenNhom+"#"+result);
		editor.commit();
	}
}
